package com.wzk.travelspringboot.global;

import com.wzk.travelspringboot.common.LogToFile;
import com.wzk.travelspringboot.controller.UserController;
import com.wzk.travelspringboot.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/4 22:33
 */
@Slf4j
@ControllerAdvice
@RestController
public class ExceptionHandler {

    public static final Logger logger = Logger.getLogger(ExceptionHandler.class.getName());

    // 捕获参数校验失败的异常（MethodArgumentNotValidException）
    @org.springframework.web.bind.annotation.ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error(ex.getMessage());
        ArrayList<String> messages = new ArrayList<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String errorMessage = error.getDefaultMessage();  // 获取错误消息
            messages.add(errorMessage);
        });
        LogToFile.logToFile("参数校验出现异常："+ex.getMessage(),logger,"validation_args_err");
        return Result.failed(messages.toString());
    }

}
